package com.example.javapoint.sync;

/**
 * 使用同步方法来操作同一个资源
 */
class SyncTable {
    public synchronized void printTable(int n) {
        for (int i = 1; i < 100; i++) {
            System.out.println( n * i);
        }
    }
}

class SyncMyThread1 extends Thread{
    SyncTable t;
    SyncMyThread1(SyncTable t) {
        this.t = t;
    }

    @Override
    public void run() {
        t.printTable(5);
        try {
            Thread.sleep(400);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class SyncMyThread2 extends Thread {
    SyncTable t;
    SyncMyThread2(SyncTable t) {
        this.t = t;
    }

    @Override
    public void run() {
        t.printTable(100);
        try {
            Thread.sleep(400);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

public class TestSynchronization2 {
    public static void main(String[] args) {
        SyncTable t = new SyncTable();
        SyncMyThread1 myThread1 = new SyncMyThread1(t);
        SyncMyThread2 myThread2 = new SyncMyThread2(t);

        myThread1.start();
        myThread2.start();
    }
}
